package com.kimo.shop.service.impl;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayConstants;
import com.alipay.api.domain.*;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.*;
import com.alipay.api.response.AlipayTradeCloseResponse;
import com.alipay.api.response.AlipayTradeQueryResponse;
import com.alipay.api.response.AlipayTradeRefundResponse;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.binarywang.wxpay.bean.notify.WxPayOrderNotifyResult;
import com.github.binarywang.wxpay.bean.notify.WxPayRefundNotifyResult;
import com.github.binarywang.wxpay.bean.order.WxPayAppOrderResult;
import com.github.binarywang.wxpay.bean.order.WxPayMpOrderResult;
import com.github.binarywang.wxpay.bean.order.WxPayMwebOrderResult;
import com.github.binarywang.wxpay.bean.order.WxPayNativeOrderResult;
import com.github.binarywang.wxpay.bean.request.WxPayRefundRequest;
import com.github.binarywang.wxpay.bean.request.WxPayUnifiedOrderRequest;
import com.github.binarywang.wxpay.bean.result.WxPayOrderQueryResult;
import com.github.binarywang.wxpay.constant.WxPayConstants;
import com.github.binarywang.wxpay.exception.WxPayException;
import com.github.binarywang.wxpay.service.WxPayService;
import com.kimo.shop.common.exception.KimoShopBindException;
import com.paypal.orders.OrdersCreateRequest;
import com.kimo.shop.bean.app.param.PayInfoParam;
import com.kimo.shop.bean.bo.PayInfoBo;
import com.kimo.shop.bean.bo.RefundInfoBo;
import com.kimo.shop.bean.event.BalancePayEvent;
import com.kimo.shop.bean.event.BalanceRefundEvent;
import com.kimo.shop.bean.model.OrderSettlement;
import com.kimo.shop.bean.param.PayPalOrderParam;
import com.kimo.shop.bean.param.WebhookParam;
import com.kimo.shop.bean.pay.PayInfoDto;
import com.kimo.shop.bean.pay.RefundInfoDto;
import com.kimo.shop.common.bean.Domain;
import com.kimo.shop.common.config.Constant;
import com.kimo.shop.common.enums.PayType;
import com.kimo.shop.common.util.Arith;
import com.kimo.shop.common.util.IPHelper;
import com.kimo.shop.config.AliPayConfig;
import com.kimo.shop.config.PayPalConfig;
import com.kimo.shop.config.ShopConfig;
import com.kimo.shop.config.WxConfig;
import com.kimo.shop.service.OrderSettlementService;
import com.kimo.shop.service.PayManagerService;
import lombok.AllArgsConstructor;
import org.springframework.context.ApplicationContext;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 统一支付工具
 *
 * @author kimo-taozhouchuan
 */
@Service
@AllArgsConstructor
public class PayManagerServiceImpl implements PayManagerService {

    private AliPayConfig aliPayConfig;

    private ShopConfig shopConfig;
    private PayPalConfig payPalConfig;

    private WxConfig wxConfig;

    private final ApplicationContext applicationContext;
    private final OrderSettlementService orderSettlementService;

    private static final String WX_SUCCESS_XML = "<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>";
    private static final String ALI_SUCCESS = "success";

    @Override
    public ResponseEntity<?> doPay(HttpServletResponse httpResponse, PayInfoDto payInfo) throws WxPayException, IOException, AlipayApiException {


        if (payInfo.getPayAmount() < 0.01 && payInfo.getIsScore() == 1) {
            return ResponseEntity.ok().build();
        }

        //微信支付不能大于1000w
        if (payInfo.getPayAmount() < 0.01 || payInfo.getPayAmount() > 10000000.00) {
            // 订单金额有误，无法进行支付
            throw new KimoShopBindException("kimo.order.amount.error");
        }
        Domain domain = shopConfig.getDomain();

        String notifyUrl = domain.getApiDomainName() + payInfo.getApiNoticeUrl();

        PayType payType = PayType.instance(payInfo.getPayType());
        if (isWxPay(payType)) {

            WxPayService wxPayService = wxConfig.getWxPayService(payType);
            WxPayUnifiedOrderRequest orderRequest = new WxPayUnifiedOrderRequest();
            orderRequest.setBody(payInfo.getBody());
            orderRequest.setOutTradeNo(payInfo.getPayNo());
            orderRequest.setTotalFee((int) Arith.mul(payInfo.getPayAmount(), 100));
            orderRequest.setSpbillCreateIp(IPHelper.getIpAddr());
            orderRequest.setOpenid(payInfo.getBizUserId());

            orderRequest.setNotifyUrl(notifyUrl);

            // 微信小程序支付
            if (Objects.equals(payType, PayType.WECHATPAY)) {
                orderRequest.setTradeType(WxPayConstants.TradeType.JSAPI);
                WxPayMpOrderResult wxPayMpOrderResult = wxPayService.createOrder(orderRequest);
                return ResponseEntity.ok(wxPayMpOrderResult);
            }
            // 微信网页支付
            else if (Objects.equals(payType, PayType.WECHATPAY_SWEEP_CODE)) {
                orderRequest.setProductId(payInfo.getPayNo());
                // 生成微信二维码
                orderRequest.setTradeType(WxPayConstants.TradeType.NATIVE);
                WxPayNativeOrderResult wxPayNativeOrderResult = wxPayService.createOrder(orderRequest);

                return ResponseEntity.ok(wxPayNativeOrderResult.getCodeUrl());
//                // 根据内部订单号更新order settlement
//                List<Order> orders = payService.paySuccess(payInfo.getPayNo(),null, PayType.WECHATPAY.value());
//
//                // 移除缓存
//                for (Order order : orders) {
//                    List<OrderItem> orderItems = order.getOrderItems();
//                    for (OrderItem orderItem : orderItems) {
//                        productService.removeProductCacheByProdId(orderItem.getProdId());
//                        skuService.removeSkuCacheBySkuId(orderItem.getSkuId(), orderItem.getProdId(), I18nMessage.getDbLang());
//                    }
//                }
//
//                return ResponseEntity.ok().build();
            }
            // 微信H5支付
            else if (Objects.equals(payType, PayType.WECHATPAY_H5)) {
                // 生成微信二维码
                orderRequest.setTradeType(WxPayConstants.TradeType.MWEB);
                String s = "{\"h5_info\": {\"type\":\"Wap\",\"wap_url\": \"\",\"wap_name\": \"\"}}";
                orderRequest.setSceneInfo(s);
                WxPayMwebOrderResult wxPayMwebOrderResult = wxPayService.createOrder(orderRequest);
                return ResponseEntity.ok(wxPayMwebOrderResult.getMwebUrl());
                // 根据内部订单号更新order settlement
//                List<Order> orders = payService.paySuccess(payInfo.getPayNo(),null, PayType.WECHATPAY.value());
//
//                // 移除缓存
//                for (Order order : orders) {
//                    List<OrderItem> orderItems = order.getOrderItems();
//                    for (OrderItem orderItem : orderItems) {
//                        productService.removeProductCacheByProdId(orderItem.getProdId());
//                        skuService.removeSkuCacheBySkuId(orderItem.getSkuId(), orderItem.getProdId(), I18nMessage.getDbLang());
//                    }
//                }
//
//                return ResponseEntity.ok().build();
            }
            // 微信公众号支付
            else if (Objects.equals(payType, PayType.WECHATPAY_MP)) {
                orderRequest.setTradeType(WxPayConstants.TradeType.JSAPI);
                WxPayMpOrderResult wxPayMpOrderResult = wxPayService.createOrder(orderRequest);
                return ResponseEntity.ok(wxPayMpOrderResult);
            }
            // 微信app支付
            else if (Objects.equals(payType, PayType.WECHATPAY_APP)) {
                orderRequest.setTradeType(WxPayConstants.TradeType.APP);
                WxPayAppOrderResult wxPayAppOrderResult = wxPayService.createOrder(orderRequest);
                return ResponseEntity.ok(wxPayAppOrderResult);
            }
        } else if (Objects.equals(payType, PayType.ALIPAY)) {
            //创建API对应的request
            AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();

            //在公共参数中设置回跳和通知地址
            alipayRequest.setNotifyUrl(notifyUrl);
            alipayRequest.setReturnUrl(payInfo.getReturnUrl());
            AlipayTradePagePayModel alipayTradePagePayModel = new AlipayTradePagePayModel();
            alipayTradePagePayModel.setOutTradeNo(payInfo.getPayNo());
            alipayTradePagePayModel.setBody(payInfo.getBody());
            alipayTradePagePayModel.setSubject(payInfo.getBody());
            alipayTradePagePayModel.setTotalAmount(Double.toString(payInfo.getPayAmount()));
            alipayTradePagePayModel.setProductCode("FAST_INSTANT_TRADE_PAY");
            alipayRequest.setBizModel(alipayTradePagePayModel);

            return ResponseEntity.ok(aliPayConfig.getAlipayClient().pageExecute(alipayRequest).getBody());
        } else if (Objects.equals(payType, PayType.ALIPAY_H5)) {

            AlipayTradeWapPayRequest alipayRequest = new AlipayTradeWapPayRequest();
            alipayRequest.setNotifyUrl(notifyUrl);
            alipayRequest.setReturnUrl(payInfo.getReturnUrl());

            AlipayTradeWapPayModel alipayTradeWapPayModel = new AlipayTradeWapPayModel();
            alipayTradeWapPayModel.setOutTradeNo(payInfo.getPayNo());
            alipayTradeWapPayModel.setSubject(payInfo.getBody());
            alipayTradeWapPayModel.setTotalAmount(Double.toString(payInfo.getPayAmount()));
            alipayTradeWapPayModel.setProductCode("QUICK_WAP_PAY");
            alipayRequest.setBizModel(alipayTradeWapPayModel);
            return ResponseEntity.ok(aliPayConfig.getAlipayClient().pageExecute(alipayRequest).getBody());
        }
        // 支付宝app支付
        else if (Objects.equals(payType, PayType.ALIPAY_APP)) {

            AlipayTradeAppPayRequest alipayRequest = new AlipayTradeAppPayRequest();
            alipayRequest.setNotifyUrl(notifyUrl);
            AlipayTradeAppPayModel alipayTradeAppPayModel = new AlipayTradeAppPayModel();
            alipayTradeAppPayModel.setOutTradeNo(payInfo.getPayNo());
            alipayTradeAppPayModel.setSubject(payInfo.getBody());
            alipayTradeAppPayModel.setTotalAmount(Double.toString(payInfo.getPayAmount()));
            alipayTradeAppPayModel.setProductCode("QUICK_MSECURITY_PAY");
            alipayRequest.setBizModel(alipayTradeAppPayModel);

            String body = aliPayConfig.getAlipayClient().sdkExecute(alipayRequest).getBody();
            return ResponseEntity.ok(body);
        }
        //余额支付
        else if (Objects.equals(payType, PayType.BALANCE)){
            PayInfoParam payInfoParam = new PayInfoParam();
            applicationContext.publishEvent(new BalancePayEvent(payInfo,payInfoParam));
            return ResponseEntity.ok(payInfoParam);
        }
        //PayPal支付
        else if (Objects.equals(payType, PayType.PAYPAL)){
            payInfo.setApiNoticeUrl(notifyUrl);
            OrdersCreateRequest request = payPalConfig.createPayPalOrder(payInfo);
            PayPalOrderParam param = payPalConfig.getExcetuteHref(request);
            // 根据支付单号，更新第三方订单号
            orderSettlementService.updateBizOrderIdByPayno(payInfo.getPayNo(),param.getOrderId());
            // 创建钩子
            payPalConfig.createWebhook(payInfo.getApiNoticeUrl());
            return ResponseEntity.ok(param.getHref());
        }
        return null;
    }

    @Override
    public PayInfoBo validateAndGetPayInfo(HttpServletRequest request, PayType payType, String xmlData) throws UnsupportedEncodingException, WxPayException, AlipayApiException {

        PayInfoBo payInfoBo = new PayInfoBo();
        // 小程序支付
        if (isWxPay(payType)) {
            WxPayService wxPayService = wxConfig.getWxPayService(payType);
            WxPayOrderNotifyResult parseOrderNotifyResult = wxPayService.parseOrderNotifyResult(xmlData);
            payInfoBo.setPayNo(parseOrderNotifyResult.getOutTradeNo());
            payInfoBo.setBizPayNo(parseOrderNotifyResult.getTransactionId());
            payInfoBo.setIsPaySuccess(true);
            payInfoBo.setSuccessString(WX_SUCCESS_XML);

        } else if (isAliPay(payType)) {
            //获取支付宝POST过来反馈信息
            Map<String, String> params = parseAliNotifyAndGetResult(request);

            if (Objects.equals(params.get("trade_status"), "TRADE_SUCCESS")) {
                //商户订单号,之前生成的带用户ID的订单号
                payInfoBo.setPayNo(params.get("out_trade_no"));
                //支付宝交易号
                payInfoBo.setBizPayNo(params.get("trade_no"));
                payInfoBo.setIsPaySuccess(true);
                payInfoBo.setSuccessString(ALI_SUCCESS);
            } else {
                payInfoBo.setIsPaySuccess(false);
            }
        }else if (Objects.equals(payType, PayType.PAYPAL)) {
            // payPal的 webHook 回调
            Map<String, String> headers= payPalConfig.getHeadersInfo(request);
            WebhookParam webhookParam = JSON.parseObject(xmlData, WebhookParam.class);
            boolean isVerify = payPalConfig.verifyWebhookSign(request,headers,xmlData);
            if (!isVerify) {
                // 验签失败
                throw new KimoShopBindException("kimo.sign.check");
            }
            String orderId = webhookParam.getResource().getId();
            if (StrUtil.isNotBlank(orderId)) {
                System.out.println("token 回调： " + orderId);
                // 查询是否支付完成如果系统订单是已经支付完成就退款
                // 通过biz_order_no  = orderId 查询到支付记录
                OrderSettlement settlement = orderSettlementService.getOne(new LambdaQueryWrapper<OrderSettlement>()
                        .eq(OrderSettlement::getBizOrderNo, orderId).last("limit 1"));
                if (Objects.isNull(settlement)) {
                    // 找不到支付记录
                    throw new KimoShopBindException("找不到支付记录");
                }
                if(Objects.equals(1,settlement.getPayStatus())) {
                    // 已支付完成,支付失败，订单不在未支付状态
                    throw new KimoShopBindException("kimo.order.pay.fail");
                }
                // 执行扣款操作
                payInfoBo = paypalCapture(orderId);
            } else {
                payInfoBo.setIsPaySuccess(false);
            }
        }
        return payInfoBo;
    }

    @Override
    public PayInfoBo getPayInfo(PayType payType, String payNo) {
        PayInfoBo payInfo = new PayInfoBo();
        payInfo.setPayNo(payNo);

        try {
            if (isWxPay(payType)) {
                WxPayService wxPayService = wxConfig.getWxPayService(payType);
                WxPayOrderQueryResult wxPayOrderQueryResult = wxPayService.queryOrder(null, payNo);
                if (!Objects.isNull(wxPayOrderQueryResult) && Objects.equals(wxPayOrderQueryResult.getTradeState(), Constant.SUCCESS)) {
                    payInfo.setBizPayNo(wxPayOrderQueryResult.getTransactionId());
                    payInfo.setIsPaySuccess(true);
                } else {
                    payInfo.setIsPaySuccess(false);
                }
            } else if (isAliPay(payType)) {
                AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();
                AlipayTradeQueryModel alipayTradeQueryModel = new AlipayTradeQueryModel();
                alipayTradeQueryModel.setOutTradeNo(payNo);

                request.setBizModel(alipayTradeQueryModel);
                AlipayTradeQueryResponse response = aliPayConfig.getAlipayClient().execute(request);
                if (response.isSuccess()) {
                    payInfo.setBizPayNo(response.getTradeNo());
                    payInfo.setIsPaySuccess(true);
                } else {
                    payInfo.setIsPaySuccess(false);
                }
            } else {
                payInfo.setIsPaySuccess(false);
            }
        } catch (WxPayException | AlipayApiException e) {
            e.printStackTrace();
            payInfo.setIsPaySuccess(false);
        }
        return payInfo;
    }

    @Override
    public boolean doRefund(RefundInfoDto refundInfo) {

        PayType payType = refundInfo.getPayType();
        if(refundInfo.getRefundAmount() == 0){
            return true;
        }
        Domain domain = shopConfig.getDomain();
        // 提交提款操作
        try {
            if (isWxPay(payType)) {
                // 退款操作
                // 生成退款请求对象
                WxPayRefundRequest wxPayRefundRequest = new WxPayRefundRequest();
                // 商户订单号
                wxPayRefundRequest.setOutTradeNo(refundInfo.getPayNo());
                // 订单金额
                double totalFee = Arith.mul(refundInfo.getPayAmount(), 100);
                wxPayRefundRequest.setTotalFee((int) totalFee);
                // 退款金额
                double refundFee = Arith.mul(refundInfo.getRefundAmount(), 100);
                wxPayRefundRequest.setRefundFee((int) refundFee);
                // 退款编码
                wxPayRefundRequest.setOutRefundNo(refundInfo.getRefundSn());


                // notifyUrl（通知结果）
                wxPayRefundRequest.setNotifyUrl(domain.getAdminDomainName() + refundInfo.getNotifyUrl());
                WxPayService wxPayService = wxConfig.getWxPayService(payType);
                wxPayService.refund(wxPayRefundRequest);

            } else if (isAliPay(payType)) {
                AlipayTradeRefundRequest request = new AlipayTradeRefundRequest();
                request.setNotifyUrl(domain.getAdminDomainName() + refundInfo.getNotifyUrl());
                AlipayTradeRefundModel alipayTradeRefundModel = new AlipayTradeRefundModel();
                alipayTradeRefundModel.setOutTradeNo(refundInfo.getPayNo());
                alipayTradeRefundModel.setRefundAmount(Double.toString(refundInfo.getRefundAmount()));
                alipayTradeRefundModel.setOutRequestNo(refundInfo.getRefundSn());
                request.setBizModel(alipayTradeRefundModel);
                AlipayTradeRefundResponse response = aliPayConfig.getAlipayClient().certificateExecute(request);
                // 对fund_change必须了解为本次退款操作，若相同退款参数调用，第一次返回fund_change=Y，第二次返回fund_change=N，但是第二次仍返回退款信息。
                if (response.isSuccess() && StrUtil.isNotBlank(response.getFundChange())) {
                    return true;
                }
            }else if (Objects.equals(payType, PayType.BALANCE)){
                applicationContext.publishEvent(new BalanceRefundEvent(refundInfo));
            }else if (Objects.equals(payType, PayType.PAYPAL)){
                // payType申请退款
                return payPalConfig.refundOrder(refundInfo);
            }
        } catch (WxPayException e) {
            e.printStackTrace();
            throw new KimoShopBindException(e.getCustomErrorMsg(), e);
        } catch (AlipayApiException e) {
            e.printStackTrace();
            throw new KimoShopBindException(e.getErrMsg(), e);
        }
        return false;
    }

    @Override
    public Boolean cancelOrderQrCode(List<OrderSettlement> orderSettlements) throws WxPayException,AlipayApiException {
        Map<Integer, String> payTypeMap = orderSettlements.stream().collect(Collectors.toMap(OrderSettlement::getPayType, OrderSettlement::getPayNo));
        for (Integer payType : payTypeMap.keySet()) {
            PayType type = PayType.instance(payType);
            if (isWxPay(type)) {
                WxPayService wxPayService = wxConfig.getWxPayService(type);
                wxPayService.closeOrder(payTypeMap.get(payType));
                return true;
            }else{
                AlipayTradeCloseRequest tradeCloseRequest = new AlipayTradeCloseRequest();
                AlipayTradeCloseModel tradeCloseModel = new AlipayTradeCloseModel();
                tradeCloseModel.setOutTradeNo(payTypeMap.get(payType));
                tradeCloseRequest.setBizModel(tradeCloseModel);
                AlipayTradeCloseResponse response = aliPayConfig.getAlipayClient().sdkExecute(tradeCloseRequest);
                if(response.isSuccess()){
                    return true;
                }
            }
        }
        return false;
    }

    @Override
    public RefundInfoBo validateAndGetRefundInfo(HttpServletRequest request, PayType payType, String xmlData) throws UnsupportedEncodingException, WxPayException, AlipayApiException {

        RefundInfoBo refundInfoBo = new RefundInfoBo();
        refundInfoBo.setIsRefundSuccess(false);

        if (isWxPay(payType)) {
            WxPayRefundNotifyResult wxPayRefundNotifyResult = wxConfig.getWxPayService(payType).parseRefundNotifyResult(xmlData);
            WxPayRefundNotifyResult.ReqInfo reqInfo = wxPayRefundNotifyResult.getReqInfo();
            //
            if ("SUCCESS".equals(reqInfo.getRefundStatus())) {
                refundInfoBo.setIsRefundSuccess(true);
                refundInfoBo.setSuccessString(WX_SUCCESS_XML);
                refundInfoBo.setRefundNo(reqInfo.getOutRefundNo());
                refundInfoBo.setBizRefundNo(reqInfo.getRefundId());
            }
        } else if (isAliPay(payType)) {
            Map<String, String> params = parseAliNotifyAndGetResult(request);
            if (Objects.equals(params.get("trade_status"), "TRADE_SUCCESS") || Objects.equals(params.get("trade_status"), "TRADE_CLOSED")) {
                refundInfoBo.setIsRefundSuccess(true);
                refundInfoBo.setRefundNo(params.get("out_biz_no"));
                refundInfoBo.setBizRefundNo("");
                refundInfoBo.setSuccessString(ALI_SUCCESS);
            }
        }


        return refundInfoBo;
    }
    @Override
    public PayInfoBo paypalCapture(String token) {
        // 执行扣款
        PayInfoBo payInfoBo = payPalConfig.captureOrder(token);
        // 查询扣款信息, 需要用到第三方交易号
//        payPalConfig.getCapture(payInfoBo.getBizPayNo());
        return payInfoBo;
    }

    //获取支付宝POST过来反馈信息
    private Map<String, String> parseAliNotifyAndGetResult(HttpServletRequest request) throws UnsupportedEncodingException, AlipayApiException {
        //乱码解决，这段代码在出现乱码时使用
        request.setCharacterEncoding("utf-8");
        //获取支付宝POST过来反馈信息
        Map<String, String> params = new HashMap<>(16);
        Map<String, String[]> requestParams = request.getParameterMap();
        for (String name : requestParams.keySet()) {
            String[] values = requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            params.put(name, valueStr);
        }
        //调用SDK验证签名
        boolean signVerified = AlipaySignature.rsaCertCheckV1(params, shopConfig.getAlipay().getAlipayCertPath(), cn.hutool.core.util.CharsetUtil.UTF_8, AlipayConstants.SIGN_TYPE_RSA2);

        if (!signVerified) {
            // 验签失败
            throw new KimoShopBindException("kimo.sign.check");
        }
        return params;
    }


    private boolean isWxPay(PayType payType) {
        return (Objects.equals(payType, PayType.WECHATPAY)
                || Objects.equals(payType, PayType.WECHATPAY_SWEEP_CODE)
                || Objects.equals(payType, PayType.WECHATPAY_H5)
                || Objects.equals(payType, PayType.WECHATPAY_MP)
                || Objects.equals(payType, PayType.WECHATPAY_APP));
    }

    private boolean isAliPay(PayType payType) {
        return (Objects.equals(payType, PayType.ALIPAY_H5)
                || Objects.equals(payType, PayType.ALIPAY)
                || Objects.equals(payType, PayType.ALIPAY_APP));
    }
}
